import { createRouter, createWebHistory } from 'vue-router'
// 一级路由
import login from '@/views/login/index.vue'
import reg from '@/views/reg/index.vue'
import home from '@/views/home/index.vue'
// 二级路由

import index from '@/views/home/children/index.vue'
import cla from '@/views/home/children/cla.vue'
import shop from '@/views/home/children/shop.vue'
import my from '@/views/home/children/my.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect:'/home/my'
    },
    {
      path: '/login',
      name: 'login',
      component: login,
    },
    {
      path: '/reg',
      name: 'reg',
      component: reg,
    },
    {
      path: '/home',
      name: 'home',
      component: home,
      children: [
        {
          path: 'index',
          name: 'index',
          component: index,
        },
        {
          path: 'cla',
          name: 'cla',
          component: cla,
        },
        {
          path: 'shop',
          name: 'shop',
          component: shop,
        },
        {
          path: 'my',
          name: 'my',
          component: my,
        },
      ]
    },
    // {
    //   path: '/about',
    //   name: 'about',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('../views/AboutView.vue'),
    // },
  ],
})

router.beforeEach((to, from, next) => {
  let isAuthenticated = localStorage.getItem('token')
  if (to.name !== 'login' && !isAuthenticated){
    next({ name: 'login' })
  } else {
    next()
  }
  
})

export default router
